﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AMS.DD35.Common.Data;
using AMS.DD35.Common;
using AMS.DD35.WebMVP.Models;
using AMS.DD35.WebMVP.Presenters;
using AMS.DD35.WcfConnector;
using AMS.DD35.WebMVP.State;

namespace AMS.DD35.WebMVP.Views
{
    public partial class CharactersView : System.Web.UI.Page, ICharactersView
    {
        CharactersPresenter _presenter;
        AMS.DD35.WebMVP.State.IStateManager _state;
        IStaticLookupService _lookup;

        #region Properties
        public long SelectedCharacterId
        {
            get
            {
                if (ddlCharacters.SelectedIndex < 0)
                    return -1;
                else
                    return long.Parse(ddlCharacters.SelectedValue);
            }
            set
            {
                for (int i = 0; i < ddlCharacters.Items.Count; i++)
                {
                    if (ddlCharacters.Items[i].Value == value.ToString())
                    {
                        ddlCharacters.SelectedIndex = i;
                        break;
                    }
                }
            }
        }

        public Dictionary<long, string> Characters
        {
            get
            {
                return ddlCharacters.DataSource as Dictionary<long, string>;
            }
            set
            {
                ddlCharacters.DataSource = value;
                ddlCharacters.DataTextField = "Value";
                ddlCharacters.DataValueField = "Key";
                ddlCharacters.DataBind();
            }
        } 
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            ICharacterService character = new CharacterProxy();
            _state = new StateManager();
            ICharacterModel model = new CharacterModel(character, _state);
            _presenter = new CharactersPresenter(this, model, _state);
            _lookup = new StaticLookupProxy();

            if (Page.IsPostBack)
                return;

            Characters = _lookup.GetCharacters(_state.SessionVariable);

        }

        public void OpenCharacter()
        {
            Response.Redirect("CharacterView.aspx", false);
        }

        protected void HandleBtnNew_Click(object sender, EventArgs args)
        {
            _presenter.NewCharacter();
        }

        protected void HandleBtnOpen_Click(object sender, EventArgs args)
        {
            _presenter.OpenCharacter();
        }
    }
}